package com.example.its2021606134chh.ThresholdModule;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ThresholdSettingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ThresholdSettingFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView textView18;
    private Switch switchAutoWarning;
    private View view;
    private TextView textView19;
    private EditText edtTemperature;
    private TextView textView20;
    private EditText edtHumidity;
    private TextView textView21;
    private EditText edtLight;
    private TextView textView22;
    private EditText edtCo2;
    private TextView textView23;
    private EditText edtPM25;
    private TextView textView24;
    private EditText edtRoad;
    private Button btnThresholdSave;
    private Timer timer;
    private TimerTask timerTask;

    public ThresholdSettingFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ThresholdSettingFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ThresholdSettingFragment newInstance(String param1, String param2) {
        ThresholdSettingFragment fragment = new ThresholdSettingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_threshold_setting, container, false);
        Handler handler = new Handler();
        Context context = getActivity().getApplicationContext();
        SharedPreferences sp = getActivity().getSharedPreferences("Threshold", Activity.MODE_PRIVATE);   //fragment中获取SharedPreferences需要多加一步getActivity()方法
        SharedPreferences.Editor editor = sp.edit();

        switchAutoWarning = (Switch) view.findViewById(R.id.switchAutoWarning);
        edtTemperature = (EditText) view.findViewById(R.id.edtTemperature);
        edtHumidity = (EditText) view.findViewById(R.id.edtHumidity);
        edtLight = (EditText) view.findViewById(R.id.edtLight);
        edtCo2 = (EditText) view.findViewById(R.id.edtCo2);
        edtPM25 = (EditText) view.findViewById(R.id.edtPM25);
        edtRoad = (EditText) view.findViewById(R.id.edtRoad);
        btnThresholdSave = (Button) view.findViewById(R.id.btnThresholdSave);

        if (sp != null) {
            edtTemperature.setText(String.valueOf(sp.getInt("Temperature", 24)));
            edtHumidity.setText(String.valueOf(sp.getInt("Humidity", 80)));
            edtLight.setText(String.valueOf(sp.getInt("Light", 2000)));
            edtCo2.setText(String.valueOf(sp.getInt("Co2", 5000)));
            edtPM25.setText(String.valueOf(sp.getInt("PM25", 150)));
            edtRoad.setText(String.valueOf(sp.getInt("Road", 0)));
        }

        if (switchAutoWarning.isChecked()) {
            editor.putBoolean("Auto On", true);
            editor.commit();
            edtTemperature.setEnabled(false);
            edtHumidity.setEnabled(false);
            edtLight.setEnabled(false);
            edtCo2.setEnabled(false);
            edtPM25.setEnabled(false);
            edtRoad.setEnabled(false);
            int ValTemperatureWarning = Integer.parseInt(edtTemperature.getText().toString());
            int ValHumidityWarning = Integer.parseInt(edtHumidity.getText().toString());
            int ValLightWarning = Integer.parseInt(edtLight.getText().toString());
            int ValCo2Warning = Integer.parseInt(edtCo2.getText().toString());
            int ValPM25Warning = Integer.parseInt(edtPM25.getText().toString());
            int ValRoadWarning = Integer.parseInt(edtRoad.getText().toString());
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
                            ThresholdParams params = gson.fromJson(json, ThresholdParams.class);
                            int Temperature = Integer.parseInt(params.getTemperature());
                            int Humidity = Integer.parseInt(params.getHumidity());
                            int LightIntensity = Integer.parseInt(params.getLightIntensity());
                            int Co2 = Integer.parseInt(params.getCo2());
                            int Pm25 = Integer.parseInt(params.getPm25());
                            String msg = "";
                            if (ValTemperatureWarning < Temperature) {
                            msg = "温度报警，阈值" + ValTemperatureWarning + "，当前值" + Temperature;
                            }
                            if (ValHumidityWarning < Humidity) {
                            msg += "湿度报警，阈值" + ValHumidityWarning + "，当前值" + Humidity;
                            }
                            if (ValLightWarning < LightIntensity) {
                            msg += "光照报警，阈值" + ValLightWarning + "，当前值" + LightIntensity;
                            }
                            if (ValCo2Warning < Co2) {
                            msg += "CO2报警，阈值" + ValCo2Warning + "，当前值" + Co2;
                            }
                            if (ValPM25Warning < Pm25) {
                            msg += "PM2.5报警，阈值" + ValPM25Warning + "，当前值" + Pm25;
                            }
                            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                        }
                    }, "get_all_sense", new String[]{"UserName"}, "user1");
                }
            };
            timer.schedule(timerTask, 0, 10000);
        } else {
            editor.putBoolean("Auto Off", false);
            editor.commit();
            edtTemperature.setEnabled(true);
            edtHumidity.setEnabled(true);
            edtLight.setEnabled(true);
            edtCo2.setEnabled(true);
            edtPM25.setEnabled(true);
            edtRoad.setEnabled(true);
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (timerTask != null) {
                timerTask.cancel();
                timerTask =  null;
            }
        }


        switchAutoWarning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (switchAutoWarning.isChecked()) {
                    editor.putBoolean("Auto On", true);
                    editor.commit();
                    edtTemperature.setEnabled(false);
                    edtHumidity.setEnabled(false);
                    edtLight.setEnabled(false);
                    edtCo2.setEnabled(false);
                    edtPM25.setEnabled(false);
                    edtRoad.setEnabled(false);
                    int ValTemperatureWarning = Integer.parseInt(edtTemperature.getText().toString());
                    int ValHumidityWarning = Integer.parseInt(edtHumidity.getText().toString());
                    int ValLightWarning = Integer.parseInt(edtLight.getText().toString());
                    int ValCo2Warning = Integer.parseInt(edtCo2.getText().toString());
                    int ValPM25Warning = Integer.parseInt(edtPM25.getText().toString());
                    int ValRoadWarning = Integer.parseInt(edtRoad.getText().toString());
                    timer = new Timer();
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                @Override
                                public void onFailure(Exception e) {

                                }

                                @Override
                                public void onResponse(String json) {
                                    Gson gson = new Gson();
                                    ThresholdParams params = gson.fromJson(json, ThresholdParams.class);
                                    int Temperature = Integer.parseInt(params.getTemperature());
                                    int Humidity = Integer.parseInt(params.getHumidity());
                                    int LightIntensity = Integer.parseInt(params.getLightIntensity());
                                    int Co2 = Integer.parseInt(params.getCo2());
                                    int Pm25 = Integer.parseInt(params.getPm25());
                                    String msg = null;
                                    if (ValTemperatureWarning < Temperature) {
                                        msg = "温度报警，阈值" + ValTemperatureWarning + "，当前值" + Temperature;
                                    }
                                    if (ValHumidityWarning < Humidity) {
                                        msg += "湿度报警，阈值" + ValHumidityWarning + "，当前值" + Humidity;
                                    }
                                    if (ValLightWarning < LightIntensity) {
                                        msg += "光照报警，阈值" + ValLightWarning + "，当前值" + LightIntensity;
                                    }
                                    if (ValCo2Warning < Co2) {
                                        msg += "CO2报警，阈值" + ValCo2Warning + "，当前值" + Co2;
                                    }
                                    if (ValPM25Warning < Pm25) {
                                        msg += "PM2.5报警，阈值" + ValPM25Warning + "，当前值" + Pm25;
                                    }
                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                }
                            }, "get_all_sense", new String[]{"UserName"}, "user1");
                        }
                    };
                    timer.schedule(timerTask, 0, 10000);
                } else {
                    editor.putBoolean("Auto Off", false);
                    editor.commit();
                    edtTemperature.setEnabled(true);
                    edtHumidity.setEnabled(true);
                    edtLight.setEnabled(true);
                    edtCo2.setEnabled(true);
                    edtPM25.setEnabled(true);
                    edtRoad.setEnabled(true);
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    if (timerTask != null) {
                        timerTask.cancel();
                        timerTask =  null;
                    }
                }
            }
        });

        btnThresholdSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = getActivity().getSharedPreferences("Threshold", Activity.MODE_PRIVATE);   //fragment中获取SharedPreferences需要多加一步getActivity()方法
                SharedPreferences.Editor editor = sp.edit();
                // Inflate the layout for this fragment
                int ValTemperatureWarning = Integer.parseInt(edtTemperature.getText().toString());
                int ValHumidityWarning = Integer.parseInt(edtHumidity.getText().toString());
                int ValLightWarning = Integer.parseInt(edtLight.getText().toString());
                int ValCo2Warning = Integer.parseInt(edtCo2.getText().toString());
                int ValPM25Warning = Integer.parseInt(edtPM25.getText().toString());
                int ValRoadWarning = Integer.parseInt(edtRoad.getText().toString());
                editor.putInt("Temperature", ValTemperatureWarning);
                editor.putInt("Humidity", ValHumidityWarning);
                editor.putInt("Light", ValLightWarning);
                editor.putInt("Co2", ValCo2Warning);
                editor.putInt("PM25", ValPM25Warning);
                editor.putInt("Road", ValRoadWarning);
                editor.commit();
            }
        });
        return view;
    }

//    @Override
//    public void onPause() {
//        if (timer != null) {
//            timer.cancel();
//            timer = null;
//        }
//        if (timerTask != null) {
//            timerTask.cancel();
//            timerTask =  null;
//        }
//        super.onPause();
//    }

    private void initView() {

    }
}